package com.emm.yixun.mobile.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetVersion;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 更新升级
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:11:52
 */
public class APKupdateActivity extends SwipeBackActivity {
	private static final String TAG = "APKupdateActivity";

	/** 界面标题 */
	TextView title_main;

	/** 返回按钮 */
	ImageView back_btn;

	/** 立即更新 */
	Button update_btn;

	TextView version_name;

	TextView new_version_name;

	TextView version_content;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;
	
	@Override
	protected void onResume() {
		BaseActivity.activity = this; // TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.apkupdate_activity);
		
		SetSwipeBackLayout(mSwipeBackLayout);
		
		BaseActivity.activity = this;

		initView();
		initBtn();
		getVersion();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:39:43
	 */
	private void initView() {
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText(getString(R.string.update_content));
		back_btn = (ImageView) findViewById(R.id.back_btn);
		update_btn = (Button) findViewById(R.id.update_btn);
		version_name = (TextView) findViewById(R.id.version_name);
		version_name.setText("当前版本：" + EmmApplication.getPackageManager(9));
		new_version_name = (TextView) findViewById(R.id.new_version_name);
		version_content = (TextView) findViewById(R.id.version_content);

		SetRelativiLayoutPadding(R.id.main_head_top_rela);

	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:39:55
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		update_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (EmmApplication.IsUpdate) {
					EmmApplication.IsUpdate = false;
					Intent updateIntent = new Intent(APKupdateActivity.this, com.eroad.product.tools.UpdateAppService.class);
					startService(updateIntent);
				} else {
					EmmApplication.Ts("下载正在进行~");
				}
				// if (EmmApplication.isDownLoadApk) {
				// DownLoad.DownLoadApk("http://oss.pgyer.com/3745c5155216e772d804a914fa589700.apk?Expires=1479292224&OSSAccessKeyId=uKgrdAVRfXyY0LsE&response-content-disposition=attachment%3B+filename%3Demm.apk&Signature=9QdcSCsHem15Diyi39FGgks5t30%3D");
				// }
			}
		});
	}

	/**
	 * 查询新版本接口
	 */
	GetVersion getversion;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 个人信息查询修改
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:40:17
	 */
	private void getVersion() {
		EmmApplication.updateUrl("getVersion");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("versionType", "1");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getVersion-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.showDialogForLoading(APKupdateActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getversion = JSONObject.parseObject(resData.toString(), GetVersion.class);

				if ("1".equals(getversion.getResult())) {
					Log.v("获取成功", "");

					if (null == getversion.getVersionName() || "".equals(getversion.getVersionName())
							|| "null".equals(getversion.getVersionName()) || TextUtils.isEmpty(getversion.getVersionName())) {
						new_version_name.setText("新版本：" + "未发现新版本");
					} else {
						new_version_name.setText("新版本：" + getversion.getVersionName());
					}

					version_content.setText(getversion.getVersionDes());

					EmmApplication.DownLoadingUrl = getversion.getVersionUrlAddress();

					if ("1".equals(getversion.getVersionStatus()) || "2".equals(getversion.getVersionStatus())) {// 可升级
						EmmApplication.isDownLoadApk = true;
						update_btn.setEnabled(true);
						update_btn.setBackgroundResource(R.drawable.suanjia_drop1);
					} else {// 不可升级
						EmmApplication.isDownLoadApk = false;
						update_btn.setEnabled(false);
						update_btn.setBackgroundResource(R.drawable.new_apk);
					}

				} else {
					EmmApplication.isDownLoadApk = false;
					update_btn.setEnabled(false);
					update_btn.setBackgroundResource(R.drawable.new_apk);
					EmmApplication.Ts(getversion.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getversion.getErrorCode().toString() + "errorMsg:" + getversion.getErrorMsg().toString());
				}
			}
		});
	}
}
